"""
@name         外呼检测
@version      1.0
@time         2025/04/06 16:50:36
@description  Retrieve data from the installation and repair pages of the installation and maintenance scheduling system every 3 minutes. 
              If there is no outbound call received from the public customer for 15 minutes and the recipient and processor are different, 
              provide DingTalk reminder. Timing rules: 21:00-8:00 is uniformly counted as 8:00, and 12:00-2:00 is uniformly counted as 2:00.
@author       liuYanXiang,652455342@qq.com
@match        http://10.245.0.60:6038/wms/
@Must-do      Fix DingRobot token and reacquire the JSESSIONID and write it to the 9_Cookie.
              If you have a better alternative to JSESSIONID, such as session, change it!
"""

import requests
from datetime import datetime, timedelta
import re
import time
import json

SENT_BUSI_NO_FILE = "9_sent_busi_no.txt"

def load_sent_busi_no():
    try:
        with open(SENT_BUSI_NO_FILE, 'r') as file:
            return set(line.strip() for line in file.readlines())
    except FileNotFoundError:
        return set()

def save_sent_busi_no(busi_no):
    with open(SENT_BUSI_NO_FILE, 'a') as file:
        file.write(busi_no + '\n')

def sendmessagetodingtalk(webhook_url, message, mobiles=[]):
    headers = {
        'Content-Type': 'application/json',
        'Charset': 'UTF-8'
    }

    payload = {
        'msgtype': 'text',
        'text': {
            'content': message
        },
        'at': {
            "atMobiles": mobiles,
            "isAtAll": False
        }
    }

    try:
        response = requests.post(webhook_url, headers=headers, data=json.dumps(payload))
        response.raise_for_status()
        result = response.json()
        if result.get('errcode') == 0:
            print('Message sent successfully.')
        else:
            print(f"Message sending failed, error message: {result.get('errmsg')}")
    except requests.RequestException as e:
        print(f'requests error: {e}')

def get_jsessionid():
    try:
        with open('9_Cookie', 'r') as file:
            for line in file:
                if line.startswith('JSESSIONID='):
                    return line.split('=')[1].strip()
    except FileNotFoundError:
        print("9_Cookie file not found.")
    return None

def getdatafromweb():
    url_install = 'http://10.245.0.60:6038/wms/orderReply/orderReplyInstallListAjax.do'
    url_repair = 'http://10.245.0.60:6038/wms/orderReply/orderReplyRepairListAjax.do'

    jsessionid = get_jsessionid()
    if jsessionid:
        mycookie = f'JSESSIONID={jsessionid}'
    else:
        print("Failed to get jsessionid from config.conf.")
        return None

    headers_install = {
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie': mycookie,
        'Host': '10.245.0.60:6038',
        'Origin': 'http://10.245.0.60:6038',
        'Referer': 'http://10.245.0.60:6038/wms/orderReply/replyInstallMenu.do',
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest'
    }

    headers_repair = {
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'Content-Length': '188',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie': mycookie,
        'Host': '10.245.0.60:6038',
        'Origin': 'http://10.245.0.60:6038',
        'Referer': 'http://10.245.0.60:6038/wms/orderReply/replyRepairMenu.do',
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest'
    }

    now = datetime.now()
    start_date = now.replace(hour=0, minute=0, second=0, microsecond=0)
    payload_install = {
        'orgId': '131000',
        'busiNo': '',
        'workAction': '0',
        'bookFlag': '0',
        'printFlag': '0',
        'custOrderCd': '',
        'orderCd': '',
        'dealUserId': '',
        'dealMan': '',
        'exchName': '',
        'startDate': start_date.strftime('%Y-%m-%d %H:%M:%S'),
        'endDate': '',
        'orderpram': 'ACCEPT_TIME',
        'orderDesc': 'DESC',
        'assignFlag': '0',
        'workStatus': '0',
        'rows': '1000',
        'page': '1'
    }

    payload_repair = {
        'orgId': '131000',
        'busiNo': "",
        'bookFlag': -1,
        'serviceName': 0,
        'custOrderCd':"",
        'orderCd':"",
        'dealUserId': "",
        'assignFlag': "0",
        'dealMan': "",
        'startDate':"",
        'endDate': "",
        'orderpram': 'CREATE_TIME',
        'orderDesc': 'DESC',
        'workStatus': '0',
        'rows': '100',
        'page': '1'
    }

    try:
        response_install = requests.post(url_install, headers=headers_install, data=payload_install)
        response_repair = requests.post(url=url_repair,headers=headers_repair,data=payload_repair)
        if response_install.status_code == 200:
            print('装机 移机 -> 请求成功')
        if response_repair.status_code == 200:
            print('修机 -> 请求成功')
        else:
            print(f'请求失败，状态码: {response_install.status_code}{response_repair.status_code}')
        result_install = response_install.json()
        result_repair = response_repair.json()
        return result_install,result_repair
    except requests.RequestException as e:
        print(e)
    return None

def fixdata():
    data_install,data_repair = getdatafromweb()
    if not data_install or 'list' not in data_install:
        return []
    now = datetime.now()
    filtered_data = []
    for item in data_install['list']:
        busi_no = item.get('BUSI_NO', '')
        service_name = item.get('SERVICE_NAME', '')
        work_action = item.get('WORK_ACTION', '')
        deal_man = item.get('DEAL_MAN', '')
        deal_man_tel = item.get('DEAL_MAN_TEL', '')
        accept_man = item.get('ACCEPT_MAN', '')
        accept_time_str = item.get('BOOK_OPT_TIME', '')
        org_name = item.get('ORG_NAME', '')
        out_call = item.get('CALL_FLAG', '')
        try:
            accept_time = datetime.strptime(accept_time_str, '%Y-%m-%d %H:%M:%S')
            # 调整 accept_time
            if 0 <= accept_time.hour < 8:
                accept_time = accept_time.replace(hour=8, minute=0, second=0, microsecond=0)
            elif 12 <= accept_time.hour < 14:
                accept_time = accept_time.replace(hour=14, minute=0, second=0, microsecond=0)
            time_diff = (now - accept_time).total_seconds() / 60
            if '拆' not in work_action and deal_man != accept_man and 15 < time_diff < 30 and out_call == 0:
                message = f"装移机30分钟内未外呼提醒\n区县：{org_name}\n号码：{busi_no}\n业务：{'装' if '装' in work_action else '移'}\n处理人：{deal_man}\n历时:{int(time_diff)}分钟\n到达公客时间：{accept_time.strftime('%Y-%m-%d %H:%M:%S')} "
                filtered_data.append((busi_no, message, deal_man_tel))
        except ValueError:
            continue

    if not data_repair or 'list' not in data_repair:
        return []
    for item in data_repair['list']:
        busi_no = item['BUSI_NO']
        service_name = item['SERVICE_NAME']
        del_man = item['DEAL_MAN']
        del_man_tel = item['DEAL_MAN_TEL']
        accept_name = item['ACCEPT_MAN']
        create_time = item['CREATE_TIME']
        book = item['BOOK']
        org_name = item['ORG_NAME']
        try:
            accept_time = datetime.strptime(create_time, '%Y-%m-%d %H:%M:%S')
            # 调整 accept_time
            if 0 <= accept_time.hour < 8:
                accept_time = accept_time.replace(hour=8, minute=0, second=0, microsecond=0)
            elif 12 <= accept_time.hour < 14:
                accept_time = accept_time.replace(hour=14, minute=0, second=0, microsecond=0)
            elif 21 <= accept_time.hour <= 23:
                accept_time = accept_time.replace(hour=8, minute=0, second=0, microsecond=0)
            time_diff = (now - accept_time).total_seconds() / 60
            if del_man != accept_name and 15 < time_diff < 30 and book == 0:
                message = f"{service_name}30分钟内未外呼提醒\n区县：{org_name}\n号码：{busi_no}\n处理人：{del_man}\n历时:{int(time_diff)}分钟\n到达公客时间：{accept_time.strftime('%Y-%m-%d %H:%M:%S')} "
                filtered_data.append((busi_no, message, del_man_tel))
        except ValueError:
            continue
    return filtered_data

if __name__ == '__main__':
    sent_busi_no = load_sent_busi_no()
    while True:
        result = fixdata()
        print("筛选结果数量:", len(result))
        for busi_no, item, tel in result:
            if busi_no not in sent_busi_no:
                m = []
                m.append(tel)
                sendmessagetodingtalk('https://oapi.dingtalk.com/robot/send?access_token=e04472180a79747393c4ca8e5440829f3231869ee7944f6abd6b4b7c11abebb5', item, m)
                print(item)
                sent_busi_no.add(busi_no)
                save_sent_busi_no(busi_no)
                time.sleep(3)
        time.sleep(120)